package com.hhs.storage.service.impl;

import com.hhs.storage.bean.*;
import com.hhs.storage.bean.dto.BusinessStats;
import com.hhs.storage.bean.dto.PriceStats;
import com.hhs.storage.bean.dto.WeightStats;
import com.hhs.storage.dao.BusinessStatsDao;
import com.hhs.storage.service.*;
import com.hhs.storage.util.SysUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: HuangHaiShui
 * @description:
 * @date: 2023/2/28 15:28
 * @version: 1.0
 */
@Service
@Lazy
@Transactional
public class BusinessStatsService {
    @Resource
    BusinessStatsDao businessStatsDao;
    @Resource
    BaseRoleService roleService;
    @Resource
    ContractService contractService;
    @Resource
    BusinessDocumentService businessDocumentService;
    @Resource
    BusinessOrderService businessOrderService;
    @Resource
    CarService carService;
    @Resource
    TypeDicService typeDicService;
    @Resource
    BaseUserService baseUserService;
    @Resource
    private HttpServletRequest request;
    @Resource
    BusinessDispatchOrderService businessDispatchOrderService;
    public Map<String, Object> carNum(StatsParam statsParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //若是业务员，只查自己的
        String userId = SysUtil.getLoginUserId(request);
        boolean flag= roleService.hasRole(SysUtil.ROLE_FLAG_YWY,userId);
        if (flag){
            statsParam.setCreater(userId);
        }

        // 获取当天日期
        LocalDate now = LocalDate.now();
        // 当天开始时间
        LocalDateTime todayStart = now.atStartOfDay();
        // 当天结束时间
        LocalDateTime todayEnd = LocalDateTime.of(now, LocalTime.MAX);
        statsParam.setStartTime(todayStart);
        statsParam.setEndTime(todayEnd);
        //今日调度车次
        statsParam.setTimeType(1);//查询createTime
        Long today = businessStatsDao.carNum(statsParam);
        resultMap.put("today", today);
        //今日完成车次
        statsParam.setTimeType(2);//查询completeTime
        Long todayComplete = businessStatsDao.carNum(statsParam);
        resultMap.put("todayComplete", todayComplete);
        //今日磅单已填写的车次
        statsParam.setSatchelFlag(1);
        Long todaySatchel = businessStatsDao.carNum(statsParam);
        resultMap.put("todaySatchel", todaySatchel);
        //当月的计算
        // 本月1号
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        // 本月最后一天
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        LocalDateTime firstDayOfMonthStart = firstDayOfMonth.atStartOfDay();
        LocalDateTime firstDayOfMonthEnd = LocalDateTime.of(lastDayOfMonth, LocalTime.MAX);
        statsParam.setStartTime(firstDayOfMonthStart);
        statsParam.setEndTime(firstDayOfMonthEnd);
        statsParam.setSatchelFlag(null);
        //本月调度车次
        statsParam.setTimeType(1);//查询createTime
        Long month = businessStatsDao.carNum(statsParam);
        resultMap.put("month", month);
        //本月完成车次
        statsParam.setTimeType(2);//查询completeTime
        Long monthComplete = businessStatsDao.carNum(statsParam);
        resultMap.put("monthComplete", monthComplete);
        //本月磅单已填写的车次
        statsParam.setSatchelFlag(1);
        Long monthSatchel = businessStatsDao.carNum(statsParam);
        resultMap.put("monthSatchel", monthSatchel);
        return ResponseInfo.success(resultMap);
    }

    public Map<String, Object> carNumDetail(StatsParam statsParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        statsParam = commonParams(statsParam);
        List<BusinessStats> detailList = businessStatsDao.carNumDetail(statsParam);
        Long total = businessStatsDao.carNum(statsParam);
        for (int i = 0; i < detailList.size(); i++) {
//            //获取了派单信息的车辆数据以及上级车队分配单信息
//            BusinessDispatchOrder temp=businessDispatchOrderService.getOtherInfo(detailList.get(i));
//            //获取合同信息
//            detailList.set(i,temp);
            BusinessStats businessStats = detailList.get(i);

            //车辆信息
            Car car=carService.getById(businessStats.getDispatchOrder().getCarId());
            businessStats.setCar(car);
            //获取下单员订单
            BusinessOrder order=businessOrderService.getById(businessStats.getOrderId());
            Region startRegion = typeDicService.formatRegion(order.getStartPlace());
            Region endRegion = typeDicService.formatRegion(order.getEndPlace());
            order.setStartRegion(startRegion);
            order.setEndRegion(endRegion);
            businessStats.setOrder(order);
            //获取业务员报单
            BusinessDocument document = businessDocumentService.getById(businessStats.getDocuId());
            businessStats.setDocument(document);
            //获取合同
            Contract contract = contractService.getById(businessStats.getContractId());
            businessStats.setContract(contract);
            //ywy
            BaseUser ywy = baseUserService.getById(contract.getCreater());
            businessStats.setYwy(ywy);
        }
        resultMap.put("total", total);
        resultMap.put("rows", detailList);
        return ResponseInfo.success(resultMap);
    }


    public Map<String, Object> priceStats(StatsParam statsParam) {
        statsParam = commonParams(statsParam);
        PriceStats priceStats = businessStatsDao.priceStats(statsParam);
        if(priceStats==null) {
            priceStats = new PriceStats();
        }
        return ResponseInfo.success(priceStats);
    }

    //已下单列表 统计每个报单已经运送的货物吨数
    public WeightStats weightStatsForTable(StatsParam statsParam) {
        WeightStats weightStats = businessStatsDao.weightStats(statsParam);
        if(weightStats==null) {
            weightStats = new WeightStats();
        }
        return weightStats;
    }

    //公共的条件生成
    private StatsParam commonParams(StatsParam statsParam){
        //若是业务员，只查自己的
        String userId = SysUtil.getLoginUserId(request);
        boolean flag= roleService.hasRole(SysUtil.ROLE_FLAG_YWY,userId);
        if (flag){
            statsParam.setCreater(userId);
        }
        //前端有传业务员进来
        if(!StringUtils.isEmpty(statsParam.getPrincipal())){
            statsParam.setCreater(statsParam.getPrincipal());
        }
        statsParam.setOffset((statsParam.getPage()-1)*statsParam.getSize());
        // 获取当天日期
        LocalDate now = LocalDate.now();
        // 当天开始时间
        LocalDateTime todayStart = now.atStartOfDay();
        // 当天结束时间
        LocalDateTime todayEnd = LocalDateTime.of(now, LocalTime.MAX);
        //当月的计算
        // 本月1号
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        // 本月最后一天
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        LocalDateTime firstDayOfMonthStart = firstDayOfMonth.atStartOfDay();
        LocalDateTime firstDayOfMonthEnd = LocalDateTime.of(lastDayOfMonth, LocalTime.MAX);

        if(statsParam.getDetailType()==1){
            //今日调度车次
            statsParam.setTimeType(1);//查询createTime
            statsParam.setStartTime(todayStart);
            statsParam.setEndTime(todayEnd);
        }else if(statsParam.getDetailType()==2){
            //本月调度车次
            statsParam.setTimeType(1);//查询createTime
            statsParam.setStartTime(firstDayOfMonthStart);
            statsParam.setEndTime(firstDayOfMonthEnd);
        }else if(statsParam.getDetailType()==3){
            //今日完成车次
            statsParam.setTimeType(2);//查询completeTime
            statsParam.setStartTime(todayStart);
            statsParam.setEndTime(todayEnd);
        }else if(statsParam.getDetailType()==4){
            //本月完成车次
            statsParam.setTimeType(2);//查询completeTime
            statsParam.setStartTime(firstDayOfMonthStart);
            statsParam.setEndTime(firstDayOfMonthEnd);
        }else if(statsParam.getDetailType()==5){
            //今日磅单已填写的车次
            statsParam.setTimeType(2);//查询completeTime
            statsParam.setSatchelFlag(1);
            statsParam.setStartTime(todayStart);
            statsParam.setEndTime(todayEnd);
        }else if(statsParam.getDetailType()==6){
            //本月磅单已填写的车次
            statsParam.setTimeType(2);//查询completeTime
            statsParam.setSatchelFlag(1);
            statsParam.setStartTime(firstDayOfMonthStart);
            statsParam.setEndTime(firstDayOfMonthEnd);
        }else if(statsParam.getStartDate()!=null && statsParam.getEndDate()!=null){
            //其他非统计明细
            statsParam.setTimeType(2);//查询completeTime
            statsParam.setStartTime(statsParam.getStartDate().atStartOfDay());
            statsParam.setEndTime(LocalDateTime.of(statsParam.getEndDate(), LocalTime.MAX));
        }
        return statsParam;
    }
}
